package com.xuyuan.interview.scene;

import com.xuyuan.interview.scene.api.Coupon;
import com.xuyuan.interview.scene.entity.Order;
import com.xuyuan.interview.scene.entity.Product;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class CouponContext implements InitializingBean {
    public static final int MAX_VALUE = Integer.MAX_VALUE;
    public static final int MIN_VALUE = Integer.MIN_VALUE;
    private static final Map<String, List<Coupon>> coupons = new HashMap<>();

    public static List<Coupon> getSpecificCoupons(String couponType) {
        return coupons.computeIfAbsent(couponType, k -> new ArrayList<>());
    }

    public static boolean addSpecificCoupon(String couponType, Coupon coupon) {
        List<Coupon> list = coupons.computeIfAbsent(couponType, k -> new ArrayList<>());
        return list.add(coupon);
    }

    public static Set<String> getAllCouponName() {
        Set<String> couponNames = coupons.keySet();
        return couponNames;
    }

    public static Coupon findPriorityCoupon(String couponType, Order order, Product product, int userLevel) {
        return Optional.ofNullable(coupons.get(couponType)).orElse(new ArrayList<>()).stream()
                .filter(coupon -> coupon.isSatisfied(order, product, userLevel)).min(Comparator.comparing(coupon -> coupon.findPriority(order))).orElse(null);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 获取所有的优惠券，初始化coupons
    }
}
